package org.example.day8;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @Description TODO
 * @Author 乐哥聊编程
 * @Date 2023/1/19 05:27
 */
public class DemoCustomPartiton {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String serverList = "192.168.64.2:9092";
        String topic = "topic_test";
        Properties prop = new Properties();

        // 2.给 Kafka 配置对象添加配置信息
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, serverList);
        // 指定分区实现配置
        prop.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, CustomPartition.class);
        // 2.2 配置 key.serializer 和 value.serializer
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class.getName());

        // 3.创建 Kafka 生产者对象
        KafkaProducer<String, Integer> kafkaProducer = new KafkaProducer<String, Integer>(prop);
        // 4.调用 send 方法，发送消息

        for (int i = 0; i < 5; i++) {
            ProducerRecord<String, Integer> record = new ProducerRecord<String, Integer>(topic,"不同的key",i);
            kafkaProducer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    System.out.println("消息所在分区："+metadata.partition());
                }
            });
        }
        Thread.sleep(10000);
    }
}
